<template>
    <!-- 对话框表单 -->
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>

        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >

                <el-form
                    ref="formRef"
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                    v-if="!baTable.form.loading"
                >

                <el-descriptions :column="2" border>
                    <el-descriptions-item :label="t('Id')">
                        {{ baTable.form.items!.id }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="t('order.order_no')">
                        {{ baTable.form.items!.order_no }}
                    </el-descriptions-item>
                      <!-- 商品信息 -->
                    <el-descriptions-item :label="t('order.goods_name')">
                        {{ baTable.form.items!.goods_name }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="t('order.goods_number')">
                        {{ baTable.form.items!.goods_number }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="t('order.goods_price')">
                        {{ baTable.form.items!.goods_price }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="t('order.goods_price')">
                        {{ baTable.form.items!.goods_price }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="baTable.form.items!.attr_1_name" v-if="baTable.form.items!.attr_1_name">
                        {{ baTable.form.items!.attr_1_value }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="baTable.form.items!.attr_2_name" v-if="baTable.form.items!.attr_2_name">
                        {{ baTable.form.items!.attr_2_value }}
                    </el-descriptions-item>

                    <el-descriptions-item :label="t('Create time')">
                        {{ timestampToDate(baTable.form.items!.ctime*1000) }}
                    </el-descriptions-item>

                    <el-descriptions-item :label="t('order.country')">
                       {{ baTable.form.items!.attr.country }}
                    </el-descriptions-item>

                    <el-descriptions-item :label="t('order.mobile')">
                         {{ baTable.form.items!.attr.mobile }}
                    </el-descriptions-item>

                    <el-descriptions-item :label="t('order.email')">
                        {{ baTable.form.items!.email }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="t('order.card_name')">
                        {{ baTable.form.items!.card_name }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="t('order.card_number')">
                        {{ baTable.form.items!.card_number }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="t('order.card_date')">
                        {{ baTable.form.items!.card_date_show }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="t('order.address')">
                        {{ baTable.form.items!.address }}
                    </el-descriptions-item>

                    <el-descriptions-item v-if="baTable.form.items!.status == 0" :label="t('order.card_cvcv')">
                        {{ baTable.form.items!.card_cvcv }}
                    </el-descriptions-item>
                    <!-- 发货信息：如果已经发货 则显示发货信息 -->
                     <template v-if="baTable.form.items!.status == 1">
                        <el-descriptions-item :label="t('order.remark')">
                           {{ baTable.form.extend!.info.remark }}
                        </el-descriptions-item>
                        <el-descriptions-item :label="t('order.send_time')">
                            {{ timestampToDate(baTable.form.extend!.info.send_time*1000) }}
                        </el-descriptions-item>
                     </template>
                </el-descriptions>


                <!-- 发货：如果还没有发货 则进行发货 -->
                <template v-if="baTable.form.extend!.info.status == 0">
                    <el-form-item :label="t('order.remark')">
                        <el-input
                            @keyup.enter.stop=""
                            @keyup.ctrl.enter="baTable.onSubmit(formRef)"
                            v-model="baTable.form.items!.remark"
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 5 }"
                            :placeholder="t('Please input field', { field: t('order.remark') })"
                        ></el-input>
                    </el-form-item>
                    <!-- <FormItem
                        :label="t('order.status')"
                        v-model="baTable.form.items!.status"
                        type="radio"
                        :input-attr="{
                            border: true,
                            content: { 1: t('order.Enable') },
                            // content: { disable: t('order.Disable'), enable: t('order.Enable') },
                        }"
                    /> -->
                </template>

            </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm('')">{{ t('Cancel') }}</el-button>
                <el-button  v-if="baTable.form.items!.status == 0" v-blur :loading="baTable.form.submitLoading" @click="baTable.onSend(formRef)" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('order.send') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, inject, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type baTableClass from '/@/utils/baTable'
import { regularPassword } from '/@/utils/validate'
import type { FormInstance, FormItemRule } from 'element-plus'
import FormItem from '/@/components/formItem/index.vue'
import router from '/@/router/index'
import { buildValidatorData } from '/@/utils/validate'
import { useConfig } from '/@/stores/config'
import createAxios from '/@/utils/axios'

const config = useConfig()
const formRef = ref<FormInstance>()
const baTable = inject('baTable') as baTableClass

const { t } = useI18n()

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    //username: [buildValidatorData({ name: 'required', title: t('member.User name') }), buildValidatorData({ name: 'account' })],
    //nickname: [buildValidatorData({ name: 'required', title: t('member.nickname') })],
    //group_id: [buildValidatorData({ name: 'required', message: t('Please select field', { field: t('member.grouping') }) })],
    email: [buildValidatorData({ name: 'email', title: t('member.email') })],
    mobile: [buildValidatorData({ name: 'mobile' })],
    status: [buildValidatorData({ name: 'required' })],
    password: [
        {
            validator: (rule: any, val: string, callback: Function) => {
                if (baTable.form.operate == 'Add') {
                    if (!val) {
                        return callback(new Error(t('Please input field', { field: t('member.password') })))
                    }
                } else {
                    if (!val) {
                        return callback()
                    }
                }
                if (!regularPassword(val)) {
                    return callback(new Error(t('validate.Please enter the correct password')))
                }
                return callback()
            },
            trigger: 'blur',
        },
    ],
})


const timestampToDate = ((timestamp, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (!timestamp) return '';

  const date = new Date(timestamp);

  // 获取日期组件
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');

  // 根据格式字符串替换
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hour)
    .replace('mm', minute)
    .replace('ss', second);
})

// 发货
// 重写表格内部的鉴权方法
baTable.onSend = (formEl: FormInstance | undefined = undefined) => {
    const operate = baTable.form.operate!.replace(baTable.form.operate![0], baTable.form.operate![0].toLowerCase())
    if (baTable.runBefore('onSubmit', { formEl: formEl, operate: operate, items: baTable.form.items! }) === false) return

    // 表单验证通过后执行的api请求操作
    const submitCallback = () => {
        baTable.form.submitLoading = true
        //baTable.api.postData(operate, baTable.form.items!)
        createAxios(
            {
                url: '/backend/order/send',
                method: 'post',
                data: {
                    id: baTable.form.items!.id,
                    status: 1,
                    //status: baTable.form.items!.status,
                    remark: baTable.form.items!.remark,
                },
            },
            {
                showSuccessMessage: true,
            }
        )
            .then((res) => {
                baTable.onTableHeaderAction('refresh', {})
                baTable.form.operateIds?.shift()
                if (baTable.form.operateIds!.length > 0) {
                    baTable.toggleForm('Show', baTable.form.operateIds)
                } else {
                    baTable.toggleForm()
                }
                baTable.runAfter('onSubmit', { res })
            })
            .finally(() => {
                baTable.form.submitLoading = false
            })
    }

    if (formEl) {
        baTable.form.ref = formEl
        formEl.validate((valid: boolean) => {
            if (valid) {
                submitCallback()
            }
        })
    } else {
        submitCallback()
    }
}

watch(
    () => baTable.form.operate,
    (newVal) => {
        rules.password![0].required = newVal == 'Add'
    }
)
</script>

<style scoped lang="scss">
.avatar-uploader {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    border-radius: var(--el-border-radius-small);
    box-shadow: var(--el-box-shadow-light);
    border: 1px dashed var(--el-border-color);
    cursor: pointer;
    overflow: hidden;
    width: 110px;
    height: 110px;
}
.avatar-uploader:hover {
    border-color: var(--el-color-primary);
}
.avatar {
    width: 110px;
    height: 110px;
    display: block;
}
.image-slot {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}
</style>
